package com.slkj.shilixiaoyuanapp.net;

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.jkyeo.basicparamsinterceptor.BasicParamsInterceptor;
import com.slkj.shilixiaoyuanapp.data.UserRequest;
import com.slkj.shilixiaoyuanapp.entity.UserEntity;
import com.slkj.shilixiaoyuanapp.net.service.CommunityService;
import com.slkj.shilixiaoyuanapp.net.service.MainPageService;
import com.slkj.shilixiaoyuanapp.net.service.ParentService;
import com.slkj.shilixiaoyuanapp.net.service.ToolService;
import com.slkj.shilixiaoyuanapp.net.service.FileService;
import com.slkj.shilixiaoyuanapp.net.service.UserService;

import java.util.concurrent.TimeUnit;

import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created  on 2018-05-18
 * @author 唐开阔
 * @describe Retrofit封装类
 * 如何取消请求？
 * Rx方式和Call方式
 */
public class HttpHeper {
    private Retrofit retrofit;
    private Object tag;
    private HttpHeper(Object object) {
         retrofit = new Retrofit.Builder()
                .baseUrl(HttpConfig.BASE_URL) // 设置 网络请求 Url
                .addConverterFactory(GsonConverterFactory.create()) //设置使用Gson解析(记得加入依赖)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(getOkHttpClient())
                .build();
        tag = object;
    }
    public <T> ObservableTransformer<T, T> getThread() {
        return upstream -> upstream.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
    }
    /**
     * 调用方式伪代码：
     * HttpHeper.from(this).xxxApi.xxx(x,y)
     * return : call  or observble
     * 手动取消 自动 取消
     * 判断是call 还是 observble
     */
    public static HttpHeper get() {
        HttpHeper httpHeper = new HttpHeper(new Object());
        return httpHeper;
    }
    public ToolService toolService(){
        return create(ToolService.class);
    }
    public CommunityService comunityService(){
        return create(CommunityService.class);
    }
    public UserService userService(){
        return create(UserService.class);
    }
    public <T> T create(final Class<T> service) {
        return retrofit.create(service);
    }
    public ParentService parentService(){
        return create(ParentService.class);
    }

    private OkHttpClient getOkHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //日志拦截器
//
//        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
//            @Override
//            public void log(String message) {
//                try {
//                    StringReader reader = new StringReader(message);
//                    Properties properties = new Properties();
//                    properties.load(reader);
//                    properties.list(System.out);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        });

        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        //添加公共的请求头
        BasicParamsInterceptor.Builder ParamBuilder = new BasicParamsInterceptor.Builder();
        if (UserRequest.getInstance().isLogin()){
            UserEntity user = UserRequest.getInstance().getUser();
            ParamBuilder.addParam("token",user.getUserToken());
            ParamBuilder.addParam("userLoginId",String.valueOf(user.getUser().getULoginUserId()));
            ParamBuilder.addParam("datasource",user.getDatasource());
            ParamBuilder.addParam("userId", String.valueOf(user.getUser().getId()));
        }
        builder.addInterceptor(ParamBuilder.build())
                .addInterceptor(httpLoggingInterceptor)
                .connectTimeout(HttpConfig.HTTP_TIME, TimeUnit.SECONDS)
                .readTimeout(HttpConfig.HTTP_TIME, TimeUnit.SECONDS)
                .writeTimeout(HttpConfig.HTTP_TIME, TimeUnit.SECONDS);
        return builder.build();
    }

    //上传图片
    public FileService updateFileService(){
        return create(FileService.class);
    }
    //通讯录
    public MainPageService mainPageService(){
        return create(MainPageService.class);
    }
}
